/*
	商品详情
	功能：
		商品详情查看
		商品信息修改
*/

//登录信息
var adminLoginedInfo = Cookies.getJSON('kplus_ad_logined_info');
var p_stock_by_size_region_tw = [], p_stock_by_size_region_cn = [];
//dom 加载完成
$(function(){
	layui.config({
	    base: './lib/layui/lay/modules/'  
	}).extend({
	    formSelects: 'formSelects'
	});
	layui.use(['layer', 'form', 'formSelects'], function(){
		var layer = layui.layer,
			form = layui.form,
			formSelects = layui.formSelects;

		var ajaxData = {
			aId: adminLoginedInfo.aId,
			aToken: adminLoginedInfo.aToken
		};
		//活动 -- 存储
		var ptl_arr = [];
		//获取商品详情
		function getProduct(ajaxData){
			var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
			var _ajaxData = $.extend({ pId : getParam('pId') }, ajaxData);
			
			$.ajax({
				url: BASE_SERVICEURL + URlS.admin_product_api,
				type: 'GET',
				data: _ajaxData,
				success: function(responseData){
					if(responseData.msg.code == 200){
						//console.log(responseData);
						//铺陈数据
						textAjaxData(responseData);
						layer.close(loadIndex);
					}else{
						layer.close(loadIndex);
						layer.msg(responseData.msg.msg, {time: 2000})
					}
				},
				error: function(responseData){
					layer.close(loadIndex);
					layer.msg(MESSAGES.service_error, {time:2000, end: function(){
						location.href = './500.html';
					}})
				}
			})
		}

		//获取活动详情
		function getAccessPromotional(ajaxData) {
            $.ajax({
                url: BASE_SERVICEURL + URlS.ptl,
                type: 'GET',
                data: ajaxData,
                success: function (responseData) {
                    if (responseData.msg.code == 200) {
                        var ptlData = responseData.data;
                        var ptlBox = $('#ptlBox');
                        for (var i = 0; i < ptlData.length; i++) {
                            var ipt = DOMHTMLSTRINGS.active_select_btn(ptlData, i);
                            ptlBox.append(ipt);
                            //ptl_arr.push(ptlData[i].wPtl);
                        }
                        form.render('checkbox');
                        // 获取商品详情
                        getProduct();
                    }else {
                        layer.msg(data.data.msg, {time: 2000});
                    }
                },
                error: function (responseData) {
                    layer.msg(MESSAGES.service_error , { time: 2000, end: function(){
                    	location.href = './500.html';
                    }});
                }
            })
        };

        getAccessPromotional(ajaxData);

		//铺陈数据
		function textAjaxData(responseData){
			var data = responseData.data;
			//console.log(data)
			var $productImgsForm = $('#product-imgs-form');
            var formInitValue = {
            	productNameCn: data.pName['cn'],
            	productNameTw: data.pName['tw'],
            	productNameEn: data.pName['en'],
            	productBrand:  data.pBrand,
            	colorIconFileSrc:data.colorIcon,
            	productSeries: data.pSeries,
            	productColor: data.pColor,
            	productPriceCn: data.pPrice['cn'],
            	productPriceTw: data.pPrice['tw'],
            	productPriceEn: data.pPrice['en'],
            	productTitleCn: data.pTitle['cn'],
            	productTitleTw: data.pTitle['tw'],
            	productTitleEn: data.pTitle['en'],
            	productSubTitleCn: data.pSubTitle['cn'],
            	productSubTitleTw: data.pSubTitle['tw'],
            	productSubTitleEn: data.pSubTitle['en'],
            	descCn: data.pBriefIntro['cn'],
            	descTw: data.pBriefIntro['tw'],
            	descEn: data.pBriefIntro['en'],
            	sortWeight: data.sortWeight
            }
            formSelects.value('size', data.pSize)

            function create_temp (size, val, region){
				return '<div class="layui-input-inline">'+
				'<input type="text" name="size_'+region+'_'+size+'" value="'+val+'" autocomplete="off" required class="layui-input" placeholder="請輸入型號'+size+'的庫存"></div>';
			}
			var str_of_sizes_tw_html = '';
			var str_of_sizes_cn_html = '';
            data.pSize.map(function(size, i){
            	var cn_val, tw_val;
            	if (data.pStock.length == 0){
            		cn_val = 0
            		tw_val = 0
            	}else{
            		if (data.pStock['cn'][i]['size'] === size){
            			cn_val = data.pStock['cn'][i]['stock']
            		}
            		if (data.pStock['tw'][i]['size'] === size){
            			tw_val = data.pStock['tw'][i]['stock']
            		}
            	}
            	str_of_sizes_tw_html += create_temp(size, tw_val, 'tw');
				str_of_sizes_cn_html += create_temp(size, cn_val, 'cn');
            })
            $('#TW_stock').append(str_of_sizes_tw_html);
            $('#CN_stock').append(str_of_sizes_cn_html);
            //勾选活动
            for(var i = 0; i < data.accessPromotional.length; i++){
            	var $ptlBox = $('#ptlBox');
            	$ptlBox.find('input[value="'+ data.accessPromotional[i] +'"]').attr('checked', true);
            	ptl_arr.push(data.accessPromotional[i]);
            }
            //推荐勾选
            if(data.isCommend == '1'){
            	$('input[name="is_commend"]').attr('checked', true);
            }
            //勾选运费叠加
            if(data.freightOverlay == 'Y'){
            	$('input[name="freightOverlay"]').attr('checked', true);
            }
            //console.log(formInitValue)
            for(var i = 0; i < data.pImg.length; i++){
            	var p_item = DOMHTMLSTRINGS.img_option_box(i);
				$productImgsForm.append(p_item);
				formInitValue['productImg' + i] = data.pImg[i];
            };
            //表单赋值
            form.val("product-detail-form", formInitValue);
            form.render();
		};
		//checkbox 复选框监听
		form.on('checkbox(ptl)', function(data){
			if(data.elem.checked){   //选中
				ptl_arr.push(data.value);
			}else{   //取消
				var index = ptl_arr.indexOf(data.value);
				ptl_arr.splice(index, index + 1);
			}
		})
		//删除商品
		form.on('submit(delete)', function(data){
			layer.confirm(MESSAGES.confirm_delete_product, {title:'提示'}, function(index){
				deleteProduct( {pId: getParam('pId')} );
				layer.close(index); //关闭询问框
			})
			function deleteProduct(data){
				var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
				var _ajaxData = $.extend({}, data, ajaxData);

				$.ajax({
					url: BASE_SERVICEURL + URlS.admin_product_api,
					type:'DELETE',
					data: _ajaxData,
					success: function(responseData){
						if(responseData.msg.code == 200){
							layer.close(loadIndex);
							layer.msg(MESSAGES.delete_product_success, {time: 2000, end: function(){
								//关闭窗口并刷新父窗口
                            	parent.layer.close(layer.index);
                            	window.parent.location.reload();
							}});
						}else{
							layer.close(loadIndex);
							layer.msg(responseData.msg.msg, {time:2000});
						}
					},
					error: function(responseData){
						layer.close(loadIndex);
						layer.msg(MESSAGES.service_error, {time: 2000, end: function(){
							location.href = './500.html';
						}})
					}
				})
			};
			return false;
		})
		//修改保存
		form.on('submit(modify)', function(data){
			formSelects.value('size', 'val').map(function(size){
				var key_tw = 'size_tw_' + size;
				var key_cn = 'size_cn_' + size;
				p_stock_by_size_region_tw.push({
					"size": size,
					"stock": data.field[key_tw]
				})
				p_stock_by_size_region_cn.push({
					"size": size,
					"stock": data.field[key_cn]
				})
			})
			//console.log(data.field);
			//console.log(p_stock_by_size_region_tw, p_stock_by_size_region_cn);
			layer.confirm(MESSAGES.confirm_modify_product, {title:'提示'}, function(index){
				//console.log(data.field);
				//return false;
				modifyProduct(data.field);
				layer.close(index); //关闭询问框
			});
			//执行函数
			function modifyProduct(field){
				//console.log(field);
				var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
				var data = field;
				var img_ipts = $('#product-imgs-form input.layui-input');
				var p_img = '';
				//console.log(data)
				var pData = {
                    pPrice: langTransObj(data.productPriceCn, data.productPriceTw, data.productPriceEn),
                    pStock: JSON.stringify({
                    	tw: p_stock_by_size_region_tw,
                    	cn: p_stock_by_size_region_cn
                    }),
                    title: langTransObj(data.productTitleCn, data.productTitleTw, data.productTitleEn),
                    subTitle: langTransObj(data.productSubTitleCn, data.productSubTitleTw, data.productSubTitleEn),
                    intro: langTransObj(data.descCn, data.descTw, data.descEn),
                    pSize: formSelects.value('size', 'val').join("|"),
                    colorIcon:data.colorIconFileSrc,
                    accessPromotional: ptl_arr.join("|"),
                    commend: data.is_commend || '0',
                    sort: data.sortWeight,
                    freight: data.freightOverlay || 'N',
                    pType: 'normal'  //该参数是用以验证权限，请勿修改
				};
				img_ipts.each(function(index ,item){
					index == img_ipts.length - 1 ? p_img = p_img + $(item).val() : p_img = p_img + $(item).val() + '|';
				})
				pData['pImg'] = p_img;
				var _ajaxData = $.extend({pId: getParam('pId')}, pData, ajaxData);
				$.ajax({
					url: BASE_SERVICEURL + URlS.admin_product_api,
					type: 'POST',
					data: _ajaxData,
					success: function(responseData){
						if(responseData.msg.code == 200){
							layer.close(loadIndex);
							layer.msg(responseData.data.msg, {time: 2000, end: function(){
								//刷新当前页
								location.reload();
							}})
						}else{
							layer.close(loadIndex);
							layer.msg(responseData.msg.msg, {time: 2000});
						}
					},
					error: function(responseData){
						layer.msg(MESSAGES.service_error, {time:2000, end: function() {
							//跳转500
							location.href = './500.html';
						}});
					}
				})
			};
			return false;	
		});

		// 创建型号对应库存
		form.on('submit(change_stock_of_psize)', function(data){
			layer.confirm("是否確認變更型號資料，如變更庫存資料會清空!", {title:'提示'}, function(index){
				var size_values = formSelects.value('size', 'val');
				function create_temp (size, region){
					return '<div class="layui-input-inline">'+
					'<input type="text" name="size_'+region+'_'+size+'" autocomplete="off" required class="layui-input" placeholder="請輸入型號'+size+'的庫存"></div>';
				}
				var str_of_sizes_tw_html = '';
				var str_of_sizes_cn_html = '';
				size_values.map(function(val){
					str_of_sizes_tw_html += create_temp(val, 'tw');
					str_of_sizes_cn_html += create_temp(val, 'cn');
				})
				//添加 
				$('#TW_stock').empty().append(str_of_sizes_tw_html);
				$('#CN_stock').empty().append(str_of_sizes_cn_html);
				form.render();
				layer.close(index); //关闭询问框
			});
			return false;
		})

	});
})





//pStock: "{"tw":[{"size":"XS","stock":"0"},{"size":"S","stock":"0"}],"cn":[{"size":"XS","stock":"0"},{"size":"S","stock":"0"}]}"

